package com.syy.quartz.job;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JobManager {
    /**
     * 新建定时任务
     * @param id 爬虫流程图
     * @return boolean true/false
     */

    public Date addJob(String id) throws SchedulerException {
        try {
            JobDetail job = JobBuilder.newJob(Job.class).withIdentity(id).build();
            job.getJobDataMap().put("SPIDER_FLOW", id);

            CronScheduleBuilder cronScheduleBuilder =
                    CronScheduleBuilder.cronSchedule("5 * * * * ?").withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("job" + id).withSchedule(cronScheduleBuilder).build();


            // Scheduler 一定是单例的
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

//            // 绑定关系是1：N ，把 JobDetail 和 Trigger绑定，注册到容器中
//            scheduler.scheduleJob(job, trigger);
//            // Scheduler 先启动后启动无所谓，只要有 Trigger 到达触发条件，就会执行任务
//            scheduler.start();



            return scheduler.scheduleJob(job,trigger);
        } catch (SchedulerException e) {
            return null;
        }
    }
}
